package com.huluobo.a2307douyindemo.shop

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.adapter.CartAdapter
import com.huluobo.a2307douyindemo.databinding.ActivityCartBinding
import com.huluobo.lib_base.bean.CartBean
import com.huluobo.lib_base.mvvm.BaseActivity
import com.huluobo.lib_base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.w3c.dom.Text

@AndroidEntryPoint
class CartActivity : BaseActivity<ActivityCartBinding, ShopViewModel>() {
    private lateinit var cartAdapter: CartAdapter
    private lateinit var cartBean: CartBean
    override fun initData() {
        vm.getCart()
        vm.getCartSuccess.observe(this) {
            cartAdapter.data.clear()
            cartAdapter.data.addAll(it)
            cartAdapter.notifyDataSetChanged()
        }

        vm.addCartSuccess.observe(this) {
            ToastUtils.showLong("修改购物车数量成功")
        }

        vm.deleteCartSuccess.observe(this) {
            ToastUtils.showLong("删除成功")
            cartAdapter.remove(cartBean)
        }
    }

    override fun initView() {
        binding.cartRv.layoutManager = LinearLayoutManager(this)
        cartAdapter = CartAdapter()
        binding.cartRv.adapter = cartAdapter

        //初始化调用一次计算总价
        totalPrice()

        cartAdapter.addChildClickViewIds(
            R.id.item_cart_cb,
            R.id.item_cart_add_btn,
            R.id.item_cart_remove_btn,
            R.id.item_cart_delete_iv
        )
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.item_cart_cb -> {
                    //是否选中取反值
                    cartAdapter.data[position].isChecked = !cartAdapter.data[position].isChecked
                    //给页面上的cb赋值
                    (adapter.getViewByPosition(position, R.id.item_cart_cb) as CheckBox).isChecked =
                        cartAdapter.data[position].isChecked
                }

                R.id.item_cart_add_btn -> {
                    cartAdapter.data[position].count++
                    //局部刷新adapter的内容
                    (adapter.getViewByPosition(position, R.id.item_cart_num_tv) as TextView).text =
                        "${cartAdapter.data[position].count}"

                    val map = mutableMapOf<String, Int>()
                    map[Const.PARAM_GOODS_ID] = cartAdapter.data[position].goods_id
                    map[Const.PARAM_COUNT] = 1

                    val json = Gson().toJson(map)
                    val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                    vm.addCart(body)
                }

                R.id.item_cart_remove_btn -> {
                    if (cartAdapter.data[position].count > 1) {
                        cartAdapter.data[position].count--
                        //局部刷新adapter的内容
                        (adapter.getViewByPosition(position, R.id.item_cart_num_tv) as TextView).text =
                            "${cartAdapter.data[position].count}"

                        val map = mutableMapOf<String, Int>()
                        map[Const.PARAM_GOODS_ID] = cartAdapter.data[position].goods_id
                        map[Const.PARAM_COUNT] = -1

                        val json = Gson().toJson(map)
                        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                        vm.addCart(body)
                    }
                }

                R.id.item_cart_delete_iv -> {
                    cartBean = cartAdapter.data[position]
                    val map = mutableMapOf<String, String>()
                    map[Const.PARAM_IDS] = cartBean.id.toString()

                    val json = Gson().toJson(map)
                    val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                    vm.deleteCart(body)
                }
            }
            checkAll()
            totalPrice()
        }

        //设置全选按钮
        binding.cartSelectAllCb.setOnCheckedChangeListener { buttonView, isChecked ->
            //当全选按钮被点击的时候,读取当前的isChecked
            binding.cartSelectAllCb.setOnClickListener {
                //遍历购物车集合数据源,修改所有的是否选中为当前全选按钮的是否选中
                cartAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                cartAdapter.notifyDataSetChanged()
                totalPrice()
            }
        }
    }

    //计算总价
    private fun totalPrice() {
        //总价
        var totalPrice = 0

        cartAdapter.data.forEach {
            if (it.isChecked) {
                totalPrice += it.goods_default_price * it.count
            }
        }

        binding.cartTotalPriceTv.text = "总价:$totalPrice"
    }

    private fun checkAll() {
        //存放所有已选中的集合
        val checkList = mutableListOf<Boolean>()
        cartAdapter.data.forEach {
            //将购物车列表中所有选中的值存放到集合中
            checkList.add(it.isChecked)
        }
        //检查false是否存在于集合中
        binding.cartSelectAllCb.isChecked = false !in checkList
    }
}